package main;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//数据操作类
public class DataAction {
	private File file = new File("data/users.dat"); // 读写文件
	private List<Map<String, String>> userList = new ArrayList<>(); // 用户集合
	private static DataAction dataAction;

	private DataAction() {
		// 若文件不存在，则创建
		if (!file.exists()) {
			try {
				if (!file.getParentFile().exists()) {
					file.getParentFile().mkdirs();
				}
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		this.readData();
	}

	// 得到实例
	public static DataAction getInstance() {
		if (dataAction == null) {
			dataAction = new DataAction();
		}
		return dataAction;
	}

	// 读用户集合
	private void readData() {
		try {
			if (file.length() > 0) { // 不是空文件才读取
				ObjectInputStream ois = new ObjectInputStream(
						new FileInputStream(file));
				userList = (List<Map<String, String>>) ois.readObject();
				ois.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	// 写用户集合
	private void writeData() {
		try {
			ObjectOutputStream oos = new ObjectOutputStream(
					new FileOutputStream(file));
			oos.writeObject(userList);
			oos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 注册
	public boolean register(Map<String, String> user) {
		if (userList.contains(user)) {
			return false;
		}
		userList.add(user);
		this.writeData();
		return true;
	}

	// 登录
	public boolean login(Map<String, String> user) {
		if (userList.contains(user)) {
			return true;
		}
		return false;
	}
}
